import Vue from 'vue'
import store from '@/store'
import { Dialog } from 'vant'
import VueRouter from 'vue-router'
import LayoutIndex from '@/views/layout/index.vue'
import LayoutHome from '@/views/layout/home.vue'
import LayoutCategory from '@/views/layout/category.vue'
import LayoutCart from '@/views/layout/cart.vue'
import LayoutUser from '@/views/layout/user.vue'

const SearchList = () => import('@/views/search/list.vue')
const ProDetail = () => import('@/views/prodetail/index.vue')
const SearchIndex = () => import('@/views/search/index.vue')
const AddAddress = () => import('@/views/address/AddAddress.vue')
const AddressList = () => import('@/views/address/AddressList.vue')
const LoginIndex = () => import('@/views/login/index.vue')
const PayPage = () => import('@/views/paypage/index.vue')
const MyOrderIndex = () => import('@/views/myorder/index.vue')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: LoginIndex },
    {
      path: '/',
      component: LayoutIndex,
      children: [
        { path: '/home', component: LayoutHome },
        { path: '/category', component: LayoutCategory },
        { path: '/cart', component: LayoutCart },
        { path: '/user', component: LayoutUser }
      ],
      redirect: '/home'
    },
    { path: '/myorder', component: MyOrderIndex },
    { path: '/paypage', component: PayPage },
    { path: '/prodetail/:id', component: ProDetail },
    { path: '/search', component: SearchIndex },
    { path: '/searchlist', component: SearchList },
    { path: '/addresslist', component: AddressList },
    { path: '/addaddress', component: AddAddress }

  ]
})

const authList = ['/myorder', '/paypage']
router.beforeEach((to, from, next) => {
  if (!authList.includes(to.path)) {
    next()
    return
  }
  if (store.getters.getToken) {
    next()
  }
  if (authList.includes(to.path) && !store.getters.getToken) {
    Dialog.confirm({
      title: '温馨提示',
      message: '此时需要先登录才能继续操作哦',
      confirmButtonText: '去登陆',
      cancelButtonText: '再逛逛'
    }).then(() => {
      // router.replace({
      //   path: '/login',
      //   query: {
      //     backUrl: this.$route.fullPath
      //   }
      // })
      next({
        path: '/login',
        query: {
          backUrl: from.fullPath
        }
      })
    }).catch(() => {})
  }
  // next('/login')
})

export default router
